package pl.edu.pw.perg.compinfodb.xls;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class XLSUtils {

	public static Properties props;
	private static final Logger logger = LoggerFactory.getLogger(XLSUtils.class);

	static {
		props = new Properties();
		
		String file = System.getProperty("file");
		if(file == null){
			logger.info("Specify properties file name: -Dfile=properties_file_name.properties");
			System.exit(1);
		}
		try {
			
			props.load(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			logger.error("File: " + file + " not found!", e);
			System.exit(1);
		} catch (IOException e) {
			logger.error("I/O Exception occured reading file: " + file, e);
			System.exit(1);
		}

	}
	public static int getColumnNr(String property){
		String[] column = getProperty(property).split(";");
		if(column.length != 2)
			throw new IllegalArgumentException("Wrong column definition");
		if(column[0].length() != 1)
			throw new IllegalArgumentException("Wrong column id");
		return convertCharToInt(column[0].charAt(0));
	}
	private static String getColumnName(String property){
		String[] column = getProperty(property).split(";");
		if(column.length != 2)
			throw new IllegalArgumentException("Wrong column definition: " + property);
		return column[1];
	}
	
	public static String getProperty(String propertyName){
		Object property = props.get(propertyName);
		if(property == null)
			throw new IllegalArgumentException("No such property: " + propertyName);
		return (String) property;
	}
	public static int getIntegerProperty(String propertyName){
		String property = getProperty(propertyName);
		int value;
		try {
			value = Integer.parseInt(property);
		} catch (NumberFormatException e) {
				throw new IllegalArgumentException("Invalid number. Property: " + propertyName + " Value: " + property);
		}
		return value;
	}
	
	static int convertCharToInt(char c) {
		return Character.getNumericValue(c) - 10;
	}

	static char convertIntToChar(int i) {
		return Character.forDigit(i + 10, 25);
	}
	
	public static String columnInt2String(int column){
		return String.valueOf(convertIntToChar(column)).toUpperCase();
	}
	
	public static Map<String, Integer> getColumnMap(String[] propertiesList){
	Map<String, Integer> columnMap = new HashMap<String, Integer>();
	for (int i = 0; i < propertiesList.length; i++) {
		Integer colId = getColumnNr(propertiesList[i]);
		String colName = getColumnName(propertiesList[i]);
		columnMap.put(colName, colId);
	}
	return columnMap;
	
}

}
